package cn.wolfcode.luowowo.feign;

import cn.wolfcode.luowowo.common.BusinessException;
import cn.wolfcode.luowowo.common.Result;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.msg.MemberCodeMsg;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.repository.UserInfoRepository;
import cn.wolfcode.luowowo.util.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wolfcode-lanxw
 */
@RestController
public class UserInfoFeignClient implements UserInfoFeignApi {
    @Autowired
    private UserInfoRepository repository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public Result checkPhone(String phone) {
        UserInfo userInfo = repository.findByPhone(phone);
        return Result.success(userInfo==null);
    }
    //思考:后端是否需要重复前端校验？　　必须要
    public Result userRegist(String phone, String nickname, String password, String rpassword) {
        //1:参数是否为空
        AssertUtils.hasLength(nickname, "昵称不能为空");
        AssertUtils.hasLength(password, "密码不能为空");
        AssertUtils.hasLength(rpassword, "确认密码不能为空");
        //2:两次输入密码是否一致
        AssertUtils.isEquals(password, rpassword, "两次输入密码不一致");
        //3:手机号码格式是否正确 @TODO  JAVA怎么执行手机号码正则表达式
        //4:手机号码是否已经注册
        UserInfo userInfo = repository.findByPhone(phone);
        if(userInfo!=null){
           return Result.error(MemberCodeMsg.PHONE_EXISTS_ERROR);
        }
        //6:用户注册
        UserInfo info = new UserInfo();
        info.setNickname(nickname);
        info.setPhone(phone);
        info.setEmail("");
        info.setPassword(password);  //假装已经加密
        info.setGender(UserInfo.GENDER_SECRET);
        info.setLevel(1);
        info.setCity("");
        info.setHeadImgUrl("/images/default.jpg");
        info.setInfo("");
        info.setState(UserInfo.STATE_NORMAL);  //明确写明状态
        info.setId(null);
        repository.save(info);
        return Result.success();
    }

    @Override
    public Result<Map> userLogin(String username, String password) {
        UserInfo userInfo = repository.findByPhoneAndPassword(username, password);
        if(userInfo == null){
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }
        userInfo.setPassword(null);  //不需要密码
        //步骤2: 创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        userInfoRedisService.setToken(token,userInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", userInfo);
        return Result.success(map);
    }
}
